package demo.db.hbase;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.List;

import org.apache.hadoop.hbase.thrift.generated.Hbase;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThriftDemo {

    private static Logger logger = LoggerFactory.getLogger(ThriftDemo.class);

    public static String byteBufferToString(ByteBuffer buffer) {
        CharBuffer charBuffer = null;
        try {
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();
            charBuffer = decoder.decode(buffer);
            buffer.flip();
            return charBuffer.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static ByteBuffer getByteBuffer(String str) {
        return ByteBuffer.wrap(str.getBytes());
    }

    private void start() {
        try {
            TTransport socket = new TSocket("172.17.16.61", 9090);// 我的虚拟机,线上用的thrift2
            TProtocol protocol = new TBinaryProtocol(socket, true, true);// 注意这里
            Hbase.Client client = new Hbase.Client(protocol);
            socket.open();
            System.out.println("open");
            try {
                System.out.println("scanning tables...");
                List<ByteBuffer> tables = client.getTableNames();
                for (ByteBuffer name : tables) {
                    System.out.println("find:" + byteBufferToString(name));
                }
            } catch (Exception e) {
                logger.error("", e);
            }
            socket.close();
            System.out.println("close");
        } catch (TTransportException e) {
            logger.error("", e);
        }
    }

    public static void main(String[] args) {
        ThriftDemo c = new ThriftDemo();
        c.start();

    }

}
